package com.xq.tmall.util;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xq.tmall.agu.core.agent.WebAgent;
import com.xq.tmall.agu.task.EasyCrawl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xiechuanxue
 * @date 2025/6/27 13:55
 * @description
 */
@Slf4j
@Component("ipFerginUtil")
public class IpFerginUtil {

    @Value("${ip.fegin.url}")
    private String ipUrl;

    @Value("${spider.useagent}")
    private String useAgent;

    @Value("${ip}")
    private String ip;

    @Value("${ip.port}")
    private String port;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisIp1() {
        String valueKey = (String) redisTemplate.opsForValue().get(RedisKey.PROXY_IP_KEY);
        // 加到缓存中
        ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
        valueOps.set(RedisKey.PROXY_IP_KEY, ip.concat(":").concat(port));
        redisTemplate.expire(RedisKey.PROXY_IP_KEY, 20, TimeUnit.MINUTES);
    }

        public Map<String,String> getRedisCookies() {
            Map<Object, Object> hashEntries = redisTemplate.opsForHash().entries(RedisKey.PROXY_COOKIES);
            Map<String, String> resultMap = new HashMap<>();
            for (Map.Entry<Object, Object> entry : hashEntries.entrySet()) {
                // 键和值在序列化时是 String 类型（因配置了 StringRedisSerializer），直接强转即可
                String key = (String) entry.getKey();
                String value = (String) entry.getValue(); // 值已通过 JSON 反序列化为 Object（如自定义对象、基本类型等）
                resultMap.put(key, value);
            }
            return resultMap;
        }

    public String getRedisIp() {
        String valueKey = (String) redisTemplate.opsForValue().get(RedisKey.PROXY_IP_KEY);
        if (StringUtils.isBlank(valueKey)) {
            return ip;
        } else {
            String redisIp = valueKey.split(":")[0];
            return redisIp;
        }
    }

    public String getRedisPort() {
        String valueKey = (String) redisTemplate.opsForValue().get(RedisKey.PROXY_IP_KEY);
        if (StringUtils.isBlank(valueKey)) {
            return port;
        }else{
            String redisPort = valueKey.split(":")[1];
            return redisPort;
        }
    }
    public void setRedisIp() {
        log.info("执行ip缓存:");
        boolean redisKey = redisTemplate.hasKey(RedisKey.PROXY_IP_KEY);
        if(redisKey){
            // 存在值，则判断是否失效
            String valueKey = (String) redisTemplate.opsForValue().get(RedisKey.PROXY_IP_KEY);
            String redisIp = valueKey.split(":")[0];
            String redisPort = valueKey.split(":")[1];
            log.info("redisIp:{}",redisIp);
            boolean available = ProxyUtils.validateIp(redisIp, Integer.valueOf(redisPort), ProxyUtils.ProxyType.HTTP);
            if (!available) {
                available = ProxyUtils.validateIp(redisIp, Integer.valueOf(redisPort), ProxyUtils.ProxyType.HTTPS);
            }
            log.info("available:{}",available);
            // 如果为true:有效不需要设置
            if(!available){
                String result = new EasyCrawl<String>()
                        .webAgent(WebAgent.defaultAgent().useAgent(useAgent).url(ipUrl))
                        .analyze(r -> r.getResult().getBody()).execute();
                log.info("获取ip服务代理:" + result);
                JSONObject jsonObject = JSON.parseObject(result);
                JSONObject ipData = jsonObject.getJSONObject("data");
                JSONArray jsonArray = ipData.getJSONArray("proxy_list");
                String ipPort = jsonArray.getString(0);
                String[] parts = ipPort.split(":");
                String ip = parts[0];
                String port = parts[1];
                // 加到缓存中
                ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
                valueOps.set(RedisKey.PROXY_IP_KEY, ip.concat(":").concat(port));
                redisTemplate.expire(RedisKey.PROXY_IP_KEY, 30, TimeUnit.MINUTES);
            }
        }else{
            String result = new EasyCrawl<String>()
                    .webAgent(WebAgent.defaultAgent().useAgent(useAgent).url(ipUrl))
                    .analyze(r -> r.getResult().getBody()).execute();
            log.info("获取ip服务代理:" + result);
            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject ipData = jsonObject.getJSONObject("data");
            JSONArray jsonArray = ipData.getJSONArray("proxy_list");
            String ipPort = jsonArray.getString(0);
            String[] parts = ipPort.split(":");
            String ip = parts[0];
            String port = parts[1];
            // 加到缓存中
            ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
            valueOps.set(RedisKey.PROXY_IP_KEY, ip.concat(":").concat(port));
            redisTemplate.expire(RedisKey.PROXY_IP_KEY, 30, TimeUnit.MINUTES);
        }
    }

  /* public void setRedisCookies() {
       String cookieUrl = "https://xueqiu.com/about/contact-us";
       // 将cookies设置到redis
       Map<Object, Object> hashEntries = redisTemplate.opsForHash().entries(RedisKey.PROXY_COOKIES);
       if (hashEntries.size() == 0) {
           Map<String, String> cookies = WebAgent.getCookies(cookieUrl);
           // 加到缓存中
           redisTemplate.opsForHash().putAll(RedisKey.PROXY_COOKIES, cookies);
           redisTemplate.expire(RedisKey.PROXY_COOKIES, 60, TimeUnit.MINUTES);
       }
   }*/

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getIpUrl() {
        return ipUrl;
    }

    public void setIpUrl(String ipUrl) {
        this.ipUrl = ipUrl;
    }

    public String getUseAgent() {
        return useAgent;
    }

    public void setUseAgent(String useAgent) {
        this.useAgent = useAgent;
    }
}
